// app/results/page.tsx
'use client';

import { useState, useEffect } from 'react';
import ResultsDisplay from '@/components/ResultsDisplay';
import { getResults, ResultsResponse } from '@/lib/api';
import Link from 'next/link';

export default function ResultsPage() {
  const [results, setResults] = useState<ResultsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [autoRefresh, setAutoRefresh] = useState(false);

  const fetchResults = async () => {
    try {
      const data = await getResults();
      setResults(data);
      setError('');
    } catch (err) {
      setError('获取投票结果失败');
      console.error('Error fetching results:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchResults();
  }, []);

  // 自动刷新功能
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (autoRefresh && results) {
      interval = setInterval(fetchResults, 3000); // 每3秒刷新一次
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [autoRefresh, results]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="text-lg mb-4">加载投票结果中...</div>
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
        </div>
      </div>
    );
  }

  if (error || !results) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="text-red-600 text-lg mb-4">{error || '获取数据失败'}</div>
          <button
            onClick={fetchResults}
            className="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700"
          >
            重试
          </button>
          <Link href="/" className="block mt-4 text-blue-600 hover:text-blue-800">
            返回投票页面
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100 py-8">
      <div className="container mx-auto px-4">
        <div className="text-center mb-8">
          <h1 className="text-4xl font-bold text-gray-800 mb-4">投票结果</h1>
          <p className="text-xl text-gray-600 mb-6">{results.topic}</p>
          
          <div className="flex justify-center space-x-4 mb-6">
            <button
              onClick={fetchResults}
              className="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700"
            >
              手动刷新
            </button>
            
            <button
              onClick={() => setAutoRefresh(!autoRefresh)}
              className={`py-2 px-4 rounded-lg ${
                autoRefresh 
                  ? 'bg-green-600 text-white hover:bg-green-700' 
                  : 'bg-gray-300 text-gray-700 hover:bg-gray-400'
              }`}
            >
              {autoRefresh ? '停止自动刷新' : '开启自动刷新'}
            </button>

            <Link
              href="/"
              className="bg-gray-600 text-white py-2 px-4 rounded-lg hover:bg-gray-700"
            >
              返回投票
            </Link>
          </div>

          {autoRefresh && (
            <div className="text-sm text-green-600 mb-4">
              ✅ 自动刷新已开启（每3秒一次）
            </div>
          )}
        </div>

        <div className="max-w-2xl mx-auto">
          <ResultsDisplay options={results.options} topic={results.topic} />
        </div>

        <div className="text-center mt-8">
          <div className="bg-white p-6 rounded-lg shadow-md">
            <h3 className="text-lg font-semibold mb-2">统计信息</h3>
            <p className="text-gray-600">
              总投票数: <span className="font-bold">{
				   results.options.reduce((sum, opt) => {
				          const votes = Number(opt.votes) || 0; // 确保是数字
				          return sum + votes;
				        }, 0)
				  }</span>
            </p>
            <p className="text-gray-600">
              选项数量: <span className="font-bold">{results.options.length}</span>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}